package oa.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

import javax.annotation.Resource;

import org.jbpm.api.Deployment;
import org.jbpm.api.ProcessDefinition;
import org.jbpm.api.ProcessDefinitionQuery;
import org.jbpm.api.ProcessEngine;
import org.springframework.stereotype.Service;

import oa.service.PDManager;

@Service("pdManager")
public class PDManagerImpl implements PDManager{

	@Resource(name="processEngine")
	private ProcessEngine processEngine;
	@Override
	public Collection<ProcessDefinition> getLasterVersion() {
		// TODO Auto-generated method stub
		Collection<ProcessDefinition> pdList = this.processEngine.getRepositoryService()
		.createProcessDefinitionQuery()
		.orderAsc(ProcessDefinitionQuery.PROPERTY_KEY)
		.list();
		
/*		Map<String,List<ProcessDefinition>> map1 = new HashMap<String, List<ProcessDefinition>>();
		for(ProcessDefinition pd:pdList){
			if(map1.containsKey(pd.getKey())){
				List<ProcessDefinition> pd2 = map1.get(pd.getKey());
				pd2.add(pd);
			}else{
				List<ProcessDefinition> pd3 = new ArrayList<ProcessDefinition>();
				pd3.add(pd);
				map1.put(pd.getKey(), pd3);
			}
		}*/
		
		Map<String, ProcessDefinition> map = new HashMap<String, ProcessDefinition>();
		for(ProcessDefinition pd:pdList){
			map.put(pd.getKey(), pd);
		}
		return map.values();
	}

	@Override
	public void deploy(File resource) throws Exception {
		// TODO Auto-generated method stub
		InputStream inputStream = new FileInputStream(resource);
		ZipInputStream zipInputStream  = new ZipInputStream(inputStream);
		this.processEngine.getRepositoryService()
		.createDeployment()
		.addResourcesFromZipInputStream(zipInputStream)
		.deploy();
	}

	@Override
	public void deletePD(String key) {
		// TODO Auto-generated method stub
		//根据key获取该key下面的所有的流程定义
		List<ProcessDefinition> pdList = this.processEngine.getRepositoryService()
		.createProcessDefinitionQuery()
		.processDefinitionKey(key)
		.list();
	    for(ProcessDefinition pd : pdList){
	    	/**
			 * 根据每一个流程定义获取到deploymentID,然后进行删除
			 */
	    	this.processEngine.getRepositoryService()
	    	.deleteDeployment(pd.getDeploymentId());
	    }
	}

	@Override
	public InputStream showImage(String deploymentId) {
		// TODO Auto-generated method stub
		/* 1、根据deploymentID和图片的路径把图片加载出来
		 * 2、把图片加载出来以后，产生输入流
		 * 3、把输入流的内容输出到界面上
		 */
        ProcessDefinition processDefinition =  this.processEngine.getRepositoryService()
		.createProcessDefinitionQuery()
		.deploymentId(deploymentId)
		.uniqueResult();
		return this.processEngine.getRepositoryService().getResourceAsStream(deploymentId, processDefinition.getImageResourceName());
	
	}

}
